#!/bin/bash

# Programmer's macOS Setup Script (China Optimized)
# For Golang, Vue, Uniapp, Python Developers
set -e

echo "🚀 开始初始化 macOS 开发环境（国内优化版）..."
echo "========================================"

# 检查是否以管理员权限运行
if [ "$EUID" -ne 0 ]; then
    echo "❌ 请使用 sudo 运行此脚本: sudo ./setup.sh"
    exit 1
fi

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 镜像地址配置
GITHUB_MIRROR="https://bgithub.xyz"
RAW_MIRROR="https://raw.bgithub.xyz"
JS_DELIVR_MIRROR="https://jsd.cdn.zzko.cn"

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
command_exists() {
    command -v "$1" &>/dev/null
}

# 检查 brew 包是否存在
brew_exists() {
    brew list --formula | grep -q "^$1$" 2>/dev/null
}

# 检查 brew cask 是否存在
cask_exists() {
    brew list --cask | grep -q "^$1$" 2>/dev/null
}

# 检查 npm 全局包是否存在
npm_global_exists() {
    npm list -g --depth=0 | grep -q " $1@"
}

# 检查 go 包是否存在
go_exists() {
    go list -m -f '{{.Path}}' "$1" &>/dev/null
}

# 安装 Homebrew（使用国内镜像）
install_homebrew() {
    if ! command_exists brew; then
        log_info "安装 Homebrew（使用国内镜像）..."

        # 使用国内镜像安装
        export HOMEBREW_BREW_GIT_REMOTE="${GITHUB_MIRROR}/Homebrew/brew.git"
        export HOMEBREW_CORE_GIT_REMOTE="${GITHUB_MIRROR}/Homebrew/homebrew-core.git"

        /bin/bash -c "$(curl -fsSL https://cdn.jsdelivr.net/gh/Homebrew/install@HEAD/install.sh)"

        # 配置 Homebrew 环境变量
        echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >>~/.zshrc
        eval "$(/opt/homebrew/bin/brew shellenv)"

        # 配置国内源
        configure_homebrew_mirror

        log_success "Homebrew 安装完成"
    else
        log_success "Homebrew 已安装，跳过安装"
        configure_homebrew_mirror
    fi
}

# 配置 Homebrew 国内镜像
configure_homebrew_mirror() {
    log_info "配置 Homebrew 国内镜像源..."

    cd "$(brew --repo)"
    git remote set-url origin "${GITHUB_MIRROR}/Homebrew/brew.git"

    cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core"
    git remote set-url origin "${GITHUB_MIRROR}/Homebrew/homebrew-core.git"

    # 设置环境变量使用国内镜像
    cat <<EOF >>~/.zshrc

# Homebrew 国内镜像配置
export HOMEBREW_BREW_GIT_REMOTE="${GITHUB_MIRROR}/Homebrew/brew.git"
export HOMEBREW_CORE_GIT_REMOTE="${GITHUB_MIRROR}/Homebrew/homebrew-core.git"
export HOMEBREW_API_DOMAIN="https://mirrors.ustc.edu.cn/homebrew-bottles/api"
export HOMEBREW_BOTTLE_DOMAIN="https://mirrors.ustc.edu.cn/homebrew-bottles"
export HOMEBREW_PIP_INDEX_URL="https://pypi.tuna.tsinghua.edu.cn/simple"
EOF

    brew update
}

# 安装开发工具
install_dev_tools() {
    log_info "安装基础开发工具..."

    # Xcode Command Line Tools
    if ! xcode-select -p &>/dev/null; then
        log_info "安装 Xcode Command Line Tools..."
        xcode-select --install
    else
        log_success "Xcode Command Line Tools 已安装，跳过安装"
    fi

    # 基础工具数组
    base_tools=("git" "wget" "curl" "tree" "htop" "neofetch" "jq" "ripgrep" "ffdiff")
    for tool in "${base_tools[@]}"; do
        if ! brew_exists "$tool"; then
            log_info "安装 $tool..."
            brew install "$tool"
        else
            log_success "$tool 已安装，跳过安装"
        fi
    done

    # Cask 工具数组
    cask_tools=("iterm2" "visual-studio-code" "postman" "docker")
    for tool in "${cask_tools[@]}"; do
        if ! cask_exists "$tool"; then
            log_info "安装 $tool..."
            brew install --cask "$tool"
        else
            log_success "$tool 已安装，跳过安装"
        fi
    done
}

# 安装 Golang 环境（使用国内镜像）
setup_golang() {
    log_info "设置 Golang 开发环境（国内镜像）..."

    if ! brew_exists "go"; then
        brew install go
    else
        log_success "Go 已安装，跳过安装"
    fi

    if ! brew_exists "golangci-lint"; then
        brew install golangci-lint
    else
        log_success "golangci-lint 已安装，跳过安装"
    fi

    # 创建 Go 工作目录
    mkdir -p ~/go/{src,bin,pkg}

    # 配置环境变量（使用国内代理）
    cat <<'EOF' >>~/.zshrc

# Golang Configuration with China Mirror
export GOPATH=$HOME/go
export GOROOT="$(brew --prefix golang)/libexec"
export PATH="$GOPATH/bin:$PATH"
export GO111MODULE=on
export GOPROXY=https://goproxy.cn,direct
export GOSUMDB=sum.golang.google.cn
export GOPRIVATE=gitlab.com,github.com
EOF

    # 安装常用 Go 工具（使用国内镜像）
    log_info "检查并安装常用 Go 开发工具（使用国内镜像）..."

    # 临时设置 GOPROXY 确保安装成功
    export GOPROXY=https://goproxy.cn,direct

    declare -A go_tools=(
        ["github.com/cosmtrek/air"]="air"
        ["github.com/go-delve/delve/cmd/dlv"]="dlv"
        ["golang.org/x/tools/cmd/goimports"]="goimports"
        ["github.com/segmentio/golines"]="golines"
        ["github.com/upx/upx"]="upx"
        ["github.com/bufbuild/buf"]="buf"
        ["github.com/google/wire/cmd/wire@latest"]="wire"
        ["github.com/owenthereal/goup/cmd/goup@latest"]="goup"
        ["github.com/golang-migrate/migrate/v4/cmd/migrate@latest"]="migrate"
    )

    for pkg in "${!go_tools[@]}"; do
        tool=${go_tools[$pkg]}
        if ! command_exists "$tool"; then
            log_info "安装 $tool..."
            go install "$pkg@latest"
        else
            log_success "$tool 已安装，跳过安装"
        fi
    done

    log_success "Golang 环境配置完成"
}

# 安装 Python 环境（使用国内镜像）
setup_python() {
    log_info "设置 Python 开发环境（国内镜像）..."

    if ! brew_exists "python@3.11"; then
        brew install python@3.11
    else
        log_success "Python 3.11 已安装，跳过安装"
    fi

    if ! brew_exists "python@3.12"; then
        brew install python@3.12
    else
        log_success "Python 3.12 已安装，跳过安装"
    fi

    if ! brew_exists "pyenv"; then
        brew install pyenv
    else
        log_success "pyenv 已安装，跳过安装"
    fi

    if ! brew_exists "pipx"; then
        brew install pipx
        pipx ensurepath
    else
        log_success "pipx 已安装，跳过安装"
    fi

    if ! brew_exists "ansible"; then
        brew install ansible
    else
        log_success "ansible 已安装，跳过安装"
    fi

    # 配置 pyenv 和 pip 国内源
    cat <<'EOF' >>~/.zshrc

# Python Configuration with China Mirror
export PYENV_ROOT="$HOME/.pyenv"
command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"

# Pip 国内镜像源
export PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
export PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
alias pip="pip --index-url=https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host=pypi.tuna.tsinghua.edu.cn"
EOF

    # 创建 pip 配置文件
    mkdir -p ~/.pip
    cat <<'EOF' >~/.pip/pip.conf
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn
timeout = 6000

[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
EOF

    # 安装常用 Python 工具（使用国内源）
    log_info "检查并安装常用 Python 工具..."

    declare -A pipx_tools=(
        ["black"]="black"
        ["flake8"]="flake8"
        ["isort"]="isort"
        ["pipenv"]="pipenv"
        ["poetry"]="poetry"
        ["ruff"]="ruff"
    )

    for tool in "${!pipx_tools[@]}"; do
        if ! command_exists "$tool"; then
            log_info "安装 $tool..."
            env PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple pipx install "$tool"
        else
            log_success "$tool 已安装，跳过安装"
        fi
    done
}

# 安装 Node.js 和前端工具（使用国内镜像）
setup_frontend() {
    log_info "设置前端开发环境（国内镜像）..."

    if ! brew_exists "nvm"; then
        brew install nvm
    else
        log_success "nvm 已安装，跳过安装"
    fi

    mkdir -p ~/.nvm

    # 配置 nvm 和 npm 国内源
    cat <<'EOF' >>~/.zshrc

# Node.js nvm Configuration
export NVM_DIR="$HOME/.nvm"
[ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh"
[ -s "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" ] && \. "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm"

# npm 国内镜像源
export npm_config_registry=https://registry.npmmirror.com
alias cnpm="npm --registry=https://registry.npmmirror.com --disturl=https://npmmirror.com/dist"
alias ynpm="npm --registry=https://registry.yarnpkg.com"
EOF

    # 加载 nvm
    export NVM_DIR="$HOME/.nvm"
    [ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh"

    # 安装 Node.js LTS
    if ! nvm ls | grep -q "lts/*"; then
        log_info "安装 Node.js LTS..."
        nvm install --lts
    else
        log_success "Node.js LTS 已安装，跳过安装"
    fi

    # 安装 Node.js 最新版本
    if ! nvm ls | grep -q "node"; then
        log_info "安装 Node.js 最新版本..."
        nvm install node
    else
        log_success "Node.js 最新版本已安装，跳过安装"
    fi

    nvm use --lts

    # 配置 npm 国内源
    npm config set registry https://registry.npmmirror.com
    npm config set disturl https://npmmirror.com/dist
    npm config set sass_binary_site https://npmmirror.com/mirrors/node-sass/
    npm config set electron_mirror https://npmmirror.com/mirrors/electron/

    # 安装 pnpm
    if ! command_exists pnpm; then
        log_info "安装 pnpm..."
        npm install -g pnpm --registry=https://registry.npmmirror.com
    else
        log_success "pnpm 已安装，跳过安装"
    fi

    # 配置 pnpm 国内源
    pnpm config set registry https://registry.npmmirror.com

    # 安装全局 npm 包（使用国内源）
    log_info "检查并安装全局 npm 包（使用国内镜像源）..."

    declare -A npm_tools=(
        ["@vue/cli"]="vue"
        ["@vue/cli-service"]="vue-cli-service"
        ["@vue/cli-plugin-typescript"]=""
        ["@vue/cli-plugin-router"]=""
        ["@vue/cli-plugin-vuex"]=""
        ["@vue/cli-plugin-eslint"]=""
        ["typescript"]="tsc"
        ["eslint"]="eslint"
        ["prettier"]="prettier"
        ["@dcloudio/uni-cli-shared"]=""
        ["@dcloudio/uni-cli-vite"]=""
        ["@dcloudio/uni-mp-vite"]=""
        ["@dcloudio/uni-app-plus"]=""
        ["@dcloudio/uni-h5"]=""
    )

    for pkg in "${!npm_tools[@]}"; do
        bin_name=${npm_tools[$pkg]}
        # 如果有二进制名称，检查二进制是否存在
        if [ -n "$bin_name" ]; then
            if ! command_exists "$bin_name"; then
                log_info "安装 $pkg..."
                npm install -g "$pkg" --registry=https://registry.npmmirror.com
            else
                log_success "$pkg 已安装，跳过安装"
            fi
        else
            # 如果没有二进制名称，检查包是否已安装
            if ! npm_global_exists "$pkg"; then
                log_info "安装 $pkg..."
                npm install -g "$pkg" --registry=https://registry.npmmirror.com
            else
                log_success "$pkg 已安装，跳过安装"
            fi
        fi
    done

    log_success "前端环境配置完成"
}

# 安装数据库和缓存
setup_databases() {
    log_info "安装数据库和缓存..."

    declare -A db_tools=(
        ["mysql"]="mysql"
        ["postgresql"]="postgres"
        ["redis"]="redis-server"
        ["mongodb/brew/mongodb-community"]="mongod"
    )

    for pkg in "${!db_tools[@]}"; do
        bin_name=${db_tools[$pkg]}
        if ! command_exists "$bin_name"; then
            log_info "安装 $pkg..."
            brew install "$pkg"
        else
            log_success "$pkg 已安装，跳过安装"
        fi
    done

    # 启动服务
    if command_exists redis-server; then
        brew services start redis
    fi
    if command_exists postgres; then
        brew services start postgresql
    fi
}

# 安装其他开发工具
install_other_tools() {
    log_info "安装其他开发工具..."

    # 终端和工具类
    declare -A dev_tools=(
        ["tmux"]="tmux"
        ["tmuxp"]="tmuxp"
        ["fd"]="fd"
        ["btop"]="btop"
        ["fzf"]="fzf"
        ["lazygit"]="lazygit"
        ["lazydocker"]="lazydocker"
        ["ripgrep"]="rg"
        ["jq"]="jq"
        ["exa"]="exa"
    )

    for pkg in "${!dev_tools[@]}"; do
        bin_name=${dev_tools[$pkg]}
        if ! command_exists "$bin_name"; then
            log_info "安装 $pkg..."
            brew install "$pkg"
        else
            log_success "$pkg 已安装，跳过安装"
        fi
    done

    # Cask 工具数组
    cask_tools=("sourcetree" "dbeaver-community" "insomnia" "raycast" "obsidian" "figma" "kitty" "localsend" "flclash")
    for tool in "${cask_tools[@]}"; do
        if ! cask_exists "$tool"; then
            log_info "安装 $tool..."
            brew install --cask "$tool"
        else
            log_success "$tool 已安装，跳过安装"
        fi
    done

    # 安装 yazi (如果不存在)
    if ! command_exists yazi; then
        log_info "安装 yazi..."
        brew install yazi
    else
        log_success "yazi 已安装，跳过安装"
    fi
}

# 配置 Docker 国内镜像
setup_docker_mirror() {
    log_info "配置 Docker 国内镜像..."

    # 创建 Docker 配置目录
    mkdir -p ~/.docker

    # 配置 Docker daemon.json
    cat <<'EOF' >~/.docker/daemon.json
{
  "registry-mirrors": [
    "https://docker.1ms.run",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com",
    "https://registry.docker-cn.com"
  ],
  "insecure-registries": [],
  "debug": true,
  "experimental": false,
  "features": {
    "buildkit": true
  }
}
EOF

    log_success "Docker 国内镜像配置完成"

    # 如果 Docker 正在运行，重启使其生效
    if command_exists docker && docker info &>/dev/null; then
        log_info "重启 Docker 使镜像配置生效..."
        if command_exists brew; then
            brew services restart docker
        fi
    fi
}

# 配置 Shell 环境（使用国内镜像）
setup_shell() {
    log_info "配置 Shell 环境（使用国内镜像）..."

    # 安装 Oh My Zsh（使用国内镜像）
    if [ ! -d "$HOME/.oh-my-zsh" ]; then
        log_info "安装 Oh My Zsh..."
        sh -c "$(curl -fsSL https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/install.sh)" "" --unattended
    else
        log_success "Oh My Zsh 已安装，跳过安装"
    fi

    # 安装 Powerlevel10k 主题（使用国内镜像）
    if [ ! -d "${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k" ]; then
        log_info "安装 Powerlevel10k 主题..."
        git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k
    else
        log_success "Powerlevel10k 已安装，跳过安装"
    fi

    # 安装 zsh 插件（使用国内镜像）
    if [ ! -d "${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions" ]; then
        log_info "安装 zsh-autosuggestions 插件..."
        git clone https://gitee.com/mirrors/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
    else
        log_success "zsh-autosuggestions 已安装，跳过安装"
    fi

    if [ ! -d "${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting" ]; then
        log_info "安装 zsh-syntax-highlighting 插件..."
        git clone https://gitee.com/mirrors/zsh-syntax-highlighting ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
    else
        log_success "zsh-syntax-highlighting 已安装，跳过安装"
    fi

    # 配置 .zshrc
    configure_zshrc
}

# 配置 .zshrc 文件
configure_zshrc() {
    log_info "配置 .zshrc 文件..."

    cat <<'EOF' >~/.zshrc
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="powerlevel10k/powerlevel10k"

plugins=(
    git
    zsh-autosuggestions
    zsh-syntax-highlighting
    docker
    docker-compose
    npm
    yarn
    fzf
    tmux
)

source $ZSH/oh-my-zsh.sh

# 自定义别名
alias ll='ls -alh'
alias cls='clear'
alias ls='exa --icons --group-directories-first'
alias la='exa -la --icons --group-directories-first'
alias tree='exa --tree --icons'

alias dc='docker-compose'
alias dcup='docker-compose up -d'
alias dcdown='docker-compose down'
alias dclogs='docker-compose logs -f'

# 工作目录快捷方式
alias gotowork='cd ~/workspace'
alias gotocode='cd ~/code'

# 开发服务器快捷方式
alias rungo='air'
alias runvue='npm run serve'
alias rununi='npm run dev:mp-weixin'

# 国内镜像快捷方式
alias npmcn='npm --registry=https://registry.npmmirror.com'
alias yarncn='yarn --registry=https://registry.npmmirror.com'
alias pipcn='pip --index-url=https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host=pypi.tuna.tsinghua.edu.cn'
alias pnpmcn='pnpm --registry=https://registry.npmmirror.com'

# fzf 配置
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
EOF

    # 添加之前的环境变量配置
    cat ~/.zshrc_temp >>~/.zshrc
    rm ~/.zshrc_temp

    log_success "Shell 环境配置完成"
}

# 创建工作目录结构
create_workspace() {
    log_info "创建工作目录结构..."

    mkdir -p ~/workspace/{projects,learning,temp,backups}
    mkdir -p ~/code/{golang,vue,uniapp,python,scripts,docker}

    log_success "工作目录创建完成"
}

# 配置 Git
setup_git() {
    log_info "配置 Git..."

    read -p "请输入你的 Git 用户名: " git_name
    read -p "请输入你的 Git 邮箱: " git_email

    git config --global user.name "$git_name"
    git config --global user.email "$git_email"
    git config --global core.editor "code --wait"
    git config --global init.defaultBranch main
    git config --global pull.rebase true
    git config --global alias.co checkout
    git config --global alias.br branch
    git config --global alias.ci commit
    git config --global alias.st status

    log_success "Git 配置完成"
}

# 安装字体（使用国内镜像）
install_fonts() {
    log_info "安装编程字体（使用国内镜像）..."

    brew tap homebrew/cask-fonts

    if ! cask_exists "font-fira-code-nerd-font"; then
        brew install --cask font-fira-code-nerd-font
    else
        log_success "Fira Code Nerd Font 已安装，跳过安装"
    fi

    if ! cask_exists "font-jetbrains-mono-nerd-font"; then
        brew install --cask font-jetbrains-mono-nerd-font
    else
        log_success "JetBrains Mono Nerd Font 已安装，跳过安装"
    fi

    log_success "字体安装完成"
}

# 配置国内镜像总结
setup_mirror_summary() {
    log_info "🎯 国内镜像配置总结："
    echo "----------------------------------------"
    echo "📦 Homebrew: 中科大镜像"
    echo "🐹 Golang: goproxy.cn 代理"
    echo "🐍 Python: 清华 PyPI 镜像"
    echo "📦 npm: npmmirror.com 镜像"
    echo "📦 pnpm: npmmirror.com 镜像"
    echo "🐳 Docker: docker.1ms.run 镜像"
    echo "🔧 Git: 使用 bgithub.xyz 镜像"
    echo "🎨 Oh My Zsh: Gitee 镜像"
    echo "----------------------------------------"
}

# 主执行函数
main() {
    log_info "开始安装程序（国内优化版）..."

    # 临时保存现有的 .zshrc 内容
    if [ -f ~/.zshrc ]; then
        cp ~/.zshrc ~/.zshrc_temp
    else
        touch ~/.zshrc_temp
    fi

    install_homebrew
    install_dev_tools
    setup_git
    setup_golang
    setup_python
    setup_frontend
    setup_databases
    install_other_tools
    setup_docker_mirror
    install_fonts
    create_workspace
    setup_shell
    setup_mirror_summary

    log_success "🎉 所有安装完成！（国内镜像优化）"
    log_warning "请执行以下命令使配置生效:"
    echo "source ~/.zshrc"
    echo "或者重新打开终端"
    echo ""
    log_info "接下来建议:"
    echo "1. 在 iTerm2/Kitty 中设置 Nerd Font 字体"
    echo "2. 运行 p10k configure 配置 Powerlevel10k 主题"
    echo "3. 在 VSCode 中安装相关扩展"
    echo "4. 在 Docker Desktop 中完成初始化设置"
    echo "5. 配置 Flclash 代理设置"
}

# 执行主函数
main "$@"
